package com.xingzhi.shortvideosharingplatform.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xingzhi.shortvideosharingplatform.common.Result;
import com.xingzhi.shortvideosharingplatform.entity.Video;
import com.xingzhi.shortvideosharingplatform.properties.JwtProperties;
import com.xingzhi.shortvideosharingplatform.service.IVideoService;
import com.xingzhi.shortvideosharingplatform.utils.JwtUtil;
import com.xingzhi.shortvideosharingplatform.vo.VideoVO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 视频信息表 前端控制器
 * </p>
 *
 * @author zjw
 * @since 2025-06-17
 */
@RestController
@RequestMapping("/video")
public class VideoController {
    @Resource
    private IVideoService videoService;
    //根据用户id获取视频列表 发布数量

    @Resource
    private JwtProperties jwtProperties;

    @GetMapping("/list/{userId}")
    public Result<List<Video>> list(@PathVariable("userId")long userId) {

        List<Video> videoList = videoService.list(new QueryWrapper<Video>().eq("user_id", userId));
        return Result.success(videoList);
    }

    //根据视频id删除视频
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id")long id) {
        boolean b = videoService.removeById(id);
        if (b) {
            return Result.success("删除成功");
        } else {
            return Result.error(400,"删除失败");
        }
    }
    //根据分类id获取这个系列视频
    @GetMapping("/listByCategory/{categoryId}")
    public Result<List<Video>> GetVideoListByCategory(@PathVariable("categoryId")long categoryId) {
        List<Video> videoList = videoService.list(new QueryWrapper<Video>().eq("category_id", categoryId));
        return Result.success(videoList);
    }

    @GetMapping("/jingxuan")
    public Result<List<VideoVO>> list() {
        List<VideoVO> videoVOList = videoService.selectVideoList(0, 5);
        return Result.success(videoVOList);
    }


    @PostMapping("/tougao")
    public Result<Video> tougao(HttpServletRequest request, @RequestBody Video video) {
        String token = request.getHeader(jwtProperties.getUserTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        Long userId = claims.get("userId", Long.class);
        video.setUserId(userId);
        videoService.save(video);
        return Result.success(video);
    }

    @GetMapping("/{id}")
    public Result<VideoVO> getVideoById(@PathVariable String id) {
        VideoVO videoVO = videoService.getVideoById(Long.valueOf(id));
        return Result.success(videoVO);
    }

}
